package cn.nawang.ebeim.client.version;

/**
 * Created by GanJc on 2016/2/23.
 */
public class HelixMatrix {

    public static void printMatrix(int n) {
        int[][] matrix = fillMatrix(n);
        System.out.println("---------------");
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(matrix[i][j] + "  ");
            }
            System.out.println();
        }
    }

    private static int[][] fillMatrix(int n) {
        int[][] matrix = new int[n][n];
        int x = 0, y = 0;
        int xd = 0, yd = 1;
        for (int i = 1; i <= n * n; i++) {
            matrix[x][y] = i;
            if (x + xd > n - 1 || x + xd < 0 || y + yd > n - 1 || y + yd < 0 || matrix[x + xd][y + yd] != 0) {
                if (xd == 0) {  //简化判断
                    xd = yd;
                    yd = 0;
                } else {
                    yd = -xd;
                    xd = 0;
                }
            }
            x += xd;
            y += yd;
        }
        return matrix;
    }


    public static void main(String[] args) {
        for (int i = 1; i < 10; i++) {
            printMatrix(i);
        }
    }
}
